<template>
  <div class="main">
    <!-- 查询区 -->
    <el-form :model="queryParams" :inline="true">
      <el-form-item label="商品编码">
        <el-input
          v-model="queryParams.productSn"
          placeholder="请输入商品编码"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="颜色">
        <el-autocomplete
          v-model="queryParams.color"
          :fetch-suggestions="(query, cb) => colorSearch(query, cb)"
          placeholder="请输入颜色"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="尺码">
        <el-autocomplete
          v-model="queryParams.size"
          :fetch-suggestions="(query, cb) => sizeSearch(query, cb)"
          placeholder="请输入尺码"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="上架状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          style="width: 130px"
        >
          <el-option label="全部" :value="undefined" />
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作区 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleDeleteBatch">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格区 -->
    <el-table
      v-loading="loading"
      :data="stockList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编码" prop="productSn" />
      <el-table-column label="商品名称" prop="productName" />
      <el-table-column label="SKU编码" prop="skuCode" />
      <el-table-column label="商品图片">
        <template #default="scope">
          <div class="image-preview">
            <img
              v-if="scope.row.skuUrl"
              :src="parseImageUrl(scope.row.skuUrl)"
              alt="商品图片"
              @error="handleImageError(scope.row)"
            />
            <span v-else>暂无图片</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="规格属性">
        <template #default="scope">
          <span>{{ scope.row.color }} / {{ scope.row.size }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="stockQuantity" />
      <el-table-column label="价格" prop="price">
        <template #default="scope"
          >￥{{ scope.row.price?.toFixed(2) }}</template
        >
      </el-table-column>
      <el-table-column label="上架状态">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="最后变动时间" prop="updateTime" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button link type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="商品编码" prop="productSn">
          <el-input v-model="form.productSn" />
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-autocomplete
            v-model="form.color"
            :fetch-suggestions="(query, cb) => colorSearch(query, cb)"
            placeholder="请输入颜色"
          />
        </el-form-item>
        <el-form-item label="尺码" prop="size">
          <el-autocomplete
            v-model="form.size"
            :fetch-suggestions="(query, cb) => sizeSearch(query, cb)"
            placeholder="请输入尺码"
          />
        </el-form-item>
        <el-form-item label="SKU编码">
          <el-input v-model="form.skuCode" disabled />
        </el-form-item>
        <el-form-item label="库存" prop="stockQuantity">
          <el-input-number
            v-model="form.stockQuantity"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="商品图片">
          <div class="upload-container">
            <el-upload
              ref="uploadRef"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              drag
              class="custom-uploader"
            >
              <div class="upload-content">
                <i class="el-icon-upload" />
                <div class="upload-text">
                  将图片拖到此处，或 <em>点击选择</em>
                </div>
              </div>
            </el-upload>
            <div v-if="form.skuUrl" class="preview-wrapper">
              <img :src="form.skuUrl" alt="商品图片" class="preview-image" />
              <div class="delete-overlay" @click="handleDeleteImage">
                <el-icon><Close /></el-icon>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Close } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  listStockByPage,
  addStock,
  updateStock,
  deleteStock,
  deleteStockBatch,
  updateStockStatus
} from "@/api/inventory";
import type {
  StockDTO,
  StockForm,
  ProductSkusCondition
} from "@/api/inventory";

// 预设选项
const COLOR_OPTIONS = ["红色", "白色", "黑色", "黄色", "灰色"].map(v => ({
  value: v
}));
const SIZE_OPTIONS = ["XS", "S", "L", "XL", "XXL"].map(v => ({ value: v }));

/** ------------------ 数据查询区 -------------------- */
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  productSn: "",
  productName: "",
  color: "",
  size: "",
  status: undefined as number | undefined
});

const stockList = ref<StockDTO[]>([]);
const total = ref(0);
const loading = ref(false);
const uploadUrl = ref("http://localhost:8080/upload");
const formRef = ref<FormInstance>();

const handleQuery = async () => {
  loading.value = true;
  try {
    const res = await listStockByPage(
      queryParams.pageNum,
      queryParams.pageSize,
      queryParams as ProductSkusCondition
    );
    stockList.value = res.data.list;
    total.value = res.data.total;
  } finally {
    loading.value = false;
  }
};

const resetQuery = () => {
  queryParams.productSn = "";
  queryParams.productName = "";
  queryParams.color = "";
  queryParams.size = "";
  queryParams.status = undefined;
  handleQuery();
};

/** ------------------ 数据操作区 -------------------- */
const dialogVisible = ref(false);
const dialogTitle = ref("新增库存");
const form = reactive<StockForm>({
  productSn: "",
  color: "",
  size: "",
  skuCode: "",
  stockQuantity: 0,
  price: 0,
  skuUrl: "",
  status: 1
});

// 表单验证规则
const rules = reactive<FormRules>({
  productSn: [{ required: true, message: "请输入商品编码", trigger: "blur" }],
  color: [{ required: true, message: "请选择颜色", trigger: "change" }],
  size: [{ required: true, message: "请选择尺码", trigger: "change" }],
  stockQuantity: [
    { required: true, message: "请输入库存数量", trigger: "blur" }
  ],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }]
});

// 自动生成SKU编码
watch(
  () => [form.productSn, form.color, form.size],
  ([sn, color, size]) => {
    if (sn && color && size) {
      form.skuCode = `${sn}-${color}-${size}`.toUpperCase().replace(/\s+/g, "");
    } else {
      form.skuCode = "";
    }
  }
);

const handleAdd = () => {
  dialogTitle.value = "新增库存";
  Object.assign(form, {
    productSn: "",
    color: "",
    size: "",
    skuCode: "",
    stockQuantity: 0,
    price: 0,
    skuUrl: "",
    status: 1
  });
  dialogVisible.value = true;
};

const handleEdit = (row: StockDTO) => {
  dialogTitle.value = "编辑库存";
  Object.assign(form, {
    ...row,
    stockQuantity: row.stockQuantity,
    price: row.price
  });
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    if (!form.skuCode) {
      return ElMessage.warning("请完善商品信息生成SKU编码");
    }

    if (dialogTitle.value === "新增库存") {
      await addStock(form);
    } else {
      await updateStock(form);
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    handleQuery();
  } catch (e) {
    console.error(e);
  }
};

/** ------------------ 删除操作 -------------------- */
const selectedSkuCodes = ref<string[]>([]);

const handleSelectionChange = (selection: StockDTO[]) => {
  selectedSkuCodes.value = selection.map(item => item.skuCode);
};

const handleDelete = async (row: StockDTO) => {
  try {
    await ElMessageBox.confirm(`确定删除SKU: ${row.skuCode}?`, "提示");
    await deleteStock(row.skuCode);
    ElMessage.success("删除成功");
    handleQuery();
  } catch {}
};

const handleDeleteBatch = async () => {
  if (selectedSkuCodes.value.length === 0) {
    return ElMessage.warning("请选择要删除的记录");
  }

  try {
    await ElMessageBox.confirm("确定批量删除选中SKU?", "警告");
    await deleteStockBatch(selectedSkuCodes.value);
    ElMessage.success("批量删除成功");
    handleQuery();
  } catch {}
};

/** ------------------ 状态切换 -------------------- */
const handleStatusChange = async (row: StockDTO) => {
  try {
    await updateStockStatus(row.skuCode);
    ElMessage.success("状态更新成功");
    handleQuery(); // 刷新列表确保状态同步
  } catch {
    row.status = row.status === 1 ? 0 : 1;
  }
};

/** ------------------ 自动完成功能 -------------------- */
const colorSearch = (query: string, cb: Function) => {
  cb(
    query ? COLOR_OPTIONS.filter(i => i.value.includes(query)) : COLOR_OPTIONS
  );
};

const sizeSearch = (query: string, cb: Function) => {
  cb(query ? SIZE_OPTIONS.filter(i => i.value.includes(query)) : SIZE_OPTIONS);
};

/** ------------------ 分页控制 -------------------- */
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  handleQuery();
};

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  handleQuery();
};

/** ------------------ 图片处理 -------------------- */
const handleUploadSuccess = (response: any) => {
  if (response.code === 200) {
    const msg = response.msg;
    const startIndex = msg.indexOf("文件地址：");
    if (startIndex !== -1) {
      form.skuUrl = msg.slice(startIndex + "文件地址：".length);
    } else {
      ElMessage.error("上传成功，但未获取到图片URL");
    }
  } else {
    ElMessage.error("上传失败：" + response.msg);
  }
};

const beforeUpload = (file: File) => {
  const isImage = ["image/jpeg", "image/png"].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传JPG/PNG格式图片!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  return true;
};

const handleDeleteImage = () => {
  form.skuUrl = "";
};

const parseImageUrl = (url: string) => {
  if (!url) return "";
  const startIndex = url.indexOf("文件地址：");
  return startIndex !== -1 ? url.slice(startIndex + "文件地址：".length) : url;
};

const handleImageError = (row: StockDTO) => {
  row.skuUrl = "";
  ElMessage.warning("图片加载失败");
};

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.image-preview {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #eee;
  img {
    max-width: 100%;
    max-height: 100%;
  }
}

.upload-container {
  position: relative;
  .preview-wrapper {
    position: relative;
    margin-top: 10px;
    .preview-image {
      max-width: 200px;
      border-radius: 4px;
    }
    .delete-overlay {
      position: absolute;
      top: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.5);
      width: 24px;
      height: 24px;
      border-radius: 0 4px 0 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      .el-icon {
        color: white;
        font-size: 16px;
      }
      &:hover {
        background: rgba(255, 0, 0, 0.7);
      }
    }
  }
}

.custom-uploader .el-upload-dragger {
  width: 360px;
  height: 180px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  &:hover {
    border-color: #409eff;
  }
}

.upload-content {
  text-align: center;
  .upload-text {
    margin-top: 10px;
    color: #666;
    em {
      color: #409eff;
      font-style: normal;
    }
  }
}
</style>
